﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel.Abstract;
using DomainModel.Entities;
using NHibernate;
using NHibernate.Criterion;

namespace DomainModel.Concrete
{
    public class EventsRepository : IEventsRepository
    {
        public IEnumerable<Event> GetAll() 
        {
            ICriteria criteria = SessionManager.CurrentSession.CreateCriteria(typeof(Event)).AddOrder(Order.Desc("EventID"));
            return criteria.List<Event>();
        }

        public Event Get(int? id)
        {
            return SessionManager.CurrentSession.Get<Event>(id);
        }

        public void Save(Event item)
        {
            ISession session = SessionManager.CurrentSession;
            session.BeginTransaction();
            session.SaveOrUpdate(item);
            session.Transaction.Commit();
        }

        public void Merge(Event item)
        {
            ISession session = SessionManager.CurrentSession;
            session.BeginTransaction();
            session.Merge(item);
            session.Transaction.Commit();
        }

        public void Delete(int id)
        {
            SessionManager.CurrentSession.Delete(Get(id));
        }

        /// <summary>
        /// Search for event's TITLE and DESCRIPTION
        /// </summary>
        /// <param name="keyword"> keyword</param>
        /// <returns></returns>
        public IEnumerable<Event> Search(string keyword)
        {
            ICriteria criteria = SessionManager.CurrentSession.CreateCriteria(typeof(Event))
                .Add(Expression.Or(Expression.Like("Title", "%" + keyword + "%").IgnoreCase(), Expression.Like("Description", "%" + keyword + "%").IgnoreCase()))
                .AddOrder(Order.Desc("EventID"));

            return criteria.List<Event>();
        }

    }
}
